class Solution {
public:
    int minimumLevels(vector<int>& p)
    {
        int ans = 0x3f3f3f3f;
        int n = p.size();
        int LC = 0;
        int DB = p[n - 1] == 0 ? -1 : 1;
        for (int i = 0; i < n - 1; i++)
        {
            if (p[i] == 0) LC--;
            else LC++;
        }
        if (LC > DB) ans = n - 1;
        for (int i = n - 2; i >= 1; i--)
        {
            if (p[i] == 0) LC++, DB--;
            else LC--, DB++;

            if (LC > DB) ans = i;
        }
        return ans == 0x3f3f3f3f ? -1 : ans;
    }
};